package com.example.market.controller;

import com.example.market.service.OrderService;
import com.example.market.util.JsonResponse;
import com.example.market.vo.CartVo;
import com.example.market.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private JsonResponse jsonResponse;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderService orderService;

    @PostMapping("")
    public JsonResponse addOrder(@RequestBody List<CartVo> cartVoList, @CookieValue("XM_TOKEN") String cookie) {
        // 先判断cookie是否存在，和redis校验
        Integer userId = (Integer) redisTemplate.opsForHash().get(cookie, "userId");
        orderService.addOrder(cartVoList, userId);
        jsonResponse.success("001", "下单成功");
        return jsonResponse;
    }

    @GetMapping("")
    public JsonResponse getOrder(@CookieValue("XM_TOKEN") String cookie) {
        // 先判断cookie是否存在，和redis校验
        Integer userId = (Integer) redisTemplate.opsForHash().get(cookie, "userId");
        List<List<OrderVo>> orders = orderService.getOrder(userId);
        Collections.sort(orders, new Comparator<List<OrderVo>>() {
            @Override
            public int compare(List<OrderVo> o1, List<OrderVo> o2) {
                Long time1 = o1.get(0).getOrderTime();
                Long time2 = o2.get(0).getOrderTime();
                if (time1 == time2) {
                    return 0;
                }else {
                    return time1 > time2 ? -1 : 1 ;
                }
            }
        });
        jsonResponse.success("001", orders);
        return jsonResponse;
    }

}
